<template>
    <div>
        <a-form @submit.prevent="handle_create_filepush" :form="form" style="padding: 0; margin-top: 20px;">
            <a-form-item label="" style="margin-bottom: 0;">
                <a-textarea :rows="3" placeholder="请输入任务动态，有文本信息才能发布" v-decorator="[
                    'content',
                    {rules: [{ required: true, message: '请输入文本信息' }]}
                ]"/>
            </a-form-item>
            <a-form-item label="">
                <div style="display: flex; justify-content: space-between; margin-top: 12px;">
                    <a-button @click="handle_show_upload_file" type='primary'> 上传附件 </a-button>
                    <a-button type='primary' html-type="submit"> 发送 </a-button>
                </div>
            </a-form-item>
            <div>
                <div style='margin-bottom: 20px;' v-for="(file, index) in push_file_list" :key="index">
                    <a-icon @click="handle_delete_push_file(file)" class="delete-icon" type="delete" />
                    {{file.filename}}.{{file.suffix}}
                </div>
            </div>
        </a-form>

                <!-- 选择附件形式 -->
        <a-modal
            title="请选择附件形式"
            :visible="push_file_visible"
            @cancel='push_file_visible=false'
            >
            <div style='height: 100px;'>
                <a-radio-group @change="handle_push_file_change_type" :default-value="1">
                    <a-radio style='display: block; height: 30px; line-height:30px;' :value="1">文件</a-radio>
                    <a-radio :value="2">Mspace报告</a-radio>
                </a-radio-group>
                <p style='color:#949494; margin-top: 20px;'>目前支持上传的格式：{{allowSuffix.map(item => item.value).join('、')}}</p>
            </div>
            <template slot="footer">
                <div style='display: flex; justify-content: space-between;'>
                    <a-button @click="push_file_visible=false">取消</a-button>
                    <a-upload
                        style='width: 300px;'
                        name="file"
                        :multiple="false"
                        :beforeUpload='this.handle_upload_before'
                        :customRequest="this.handle_upload_file"
                        :showUploadList="false"
                        >
                        <a-button type='primary'> <a-icon type="link" /> 确定 </a-button>
                    </a-upload>
                </div>
            </template>

        </a-modal>
    </div>
</template>

<script>
    import config from '@/api/config'
    
    export default {
        props: {
            create_push: {
                type: Function,
                default: () => {}
            }
        },
        data(){
            return {
                form: this.$form.createForm(this),
                push_file_visible: false,
                push_file_type: 1,
                push_files: {},
                push_file_list: [],
                allowSuffix: [
                    { label: 'pdf', value: 'pdf'},
                    { label: 'doc', value: 'doc'},
                    { label: 'docx', value: 'docx'},
                    { label: 'xls', value: 'xls'},
                    { label: 'xlsx', value: 'xlsx'},
                    { label: 'zip', value: 'zip'},
                    { label: 'jpg', value: 'jpg'},
                    { label: 'png', value: 'png'},
                    { label: 'Mspace报告', value: 'Mspace报告'},
                ]
            }
        },
        watch: {
            'push_file_list': {
                handler(value){
                    let first = value[0]
                    this.$nextTick(() => {
                        this.form.setFieldsValue({
                            content: (first && first.filename) || ''
                        })
                    })
                },
                deep: true
            }
        },
        methods: {
            /** 显示选择附件形式弹窗 */
            handle_show_upload_file(){
                this.push_file_visible = true
            },
            /** 请选择附件形式 */
            handle_push_file_change_type(e){
                this.push_file_type = e.target.value
            },
            handle_upload_before(file){

                let fileName = file.name,
                    name = fileName.substring(0, fileName.lastIndexOf('.')),
                    suffix = fileName.substring(fileName.lastIndexOf('.')+1, fileName.length)
                console.log('file:', file)
                // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                // if (!isJpgOrPng) {
                //     this.$message.error('You can only upload JPG file!');
                // }
                const isLt20M = file.size / 1024 / 1024 < 20;
                if (!isLt20M) {
                    this.$message.error('Image must smaller than 20MB!');
                }

                if(suffix && this.allowSuffix.map(item => item.value).includes(suffix)){
                    return true
                }else{
                    this.$message.error('格式错误', 1);
                    return false
                }
            },
            /** 上传文件 */
            handle_upload_file(args){
                if(args){
                    let fileName = args.file.name,
                        name = fileName.substring(0, fileName.lastIndexOf('.')),
                        suffix = fileName.substring(fileName.lastIndexOf('.')+1, fileName.length),
                        size = args.file.size

                    let params = new FormData();
                    params.append("video", args.file);
                    this.http(
                        "post",
                        config.uploadURL,
                        params
                    ).then(resp => {
                        let item = {
                            filename: name,
                            suffix: suffix,
                            size: size,
                            url: resp.url,
                            type: this.push_file_type
                        }
                        console.log('item:', item, args.file.uid)
                        this.push_files[args.file.uid] = item
                        this.push_file_list.push({
                            id: args.file.uid,
                            ...item
                        })
                        this.$message.success('上传成功', 1);
                        this.push_file_visible = false
                        return args.onSuccess({code:200}, args.file);
                    }).catch(e => console.error(e))
                }else{
                    this.push_file_visible = false
                }
            },
            /** 删除上传的文件 */
            handle_delete_push_file(file){
                this.$confirm({
                    title: '系统提示',
                    content: '确定要删除该文件么？',
                    okText: '确认',
                    cancelText: '取消',
                    onOk: close => {
                        const { push_file_list } = this
                        this.push_files[file.id] = undefined
                        let index = push_file_list.findIndex(item => item.id === file.id)
                        if(index !== -1){
                            this.push_file_list.splice(index, 1)
                        }
                        console.log("this.push_files----->",this.push_files);
                        console.log("this.push_file_list---->",this.push_file_list);
                        close()
                    }
                });
            },
            /** 创建文件类型的推送 */
            handle_create_filepush(){
                this.form.validateFields(async (err, values) => {
                    if(!err){
                        const { push_files } = this
                        let images = []
                        Object.keys(push_files).forEach(key => {
                            if(push_files[key]){
                                images.push(push_files[key])
                            }
                        })
                        values.images = images
                        let resp = await this.create_push(values)

                        console.log('resp:', resp)

                        if(resp){
                            this.form.resetFields()
                            this.push_files = {}
                            this.push_file_list = []
                        }
                    }
                })
            },
        }
    }
</script>

<style lang="scss" scoped>

    .delete-icon{
        margin-left: 20px; 
        color: #fff; 
        cursor: pointer;
        &:hover{
            color: red;
        }
    }

</style>